package com.deyuanyun.pic.insp.service.inspresult.impl;

import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.web.RequestResponseContext;
import com.deyuanyun.pic.insp.mapper.DefectMetalLossMapper;
import com.deyuanyun.pic.insp.mapper.InspStatMapper;
import com.deyuanyun.pic.insp.service.inspresult.InspCommService;
import com.deyuanyun.pic.settings.support.biz.CodeUtil;
import com.github.pagehelper.PageHelper;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 模块描述
 *
 * @author scalpel.王敏
 * @version [v1.0] 创建时间（2016/8/8）
 * @see // 引用的类
 * Method List:
 * 1.----------------
 * 2.----------------
 * History:
 */
public abstract class BaseServiceImpl {



    @Resource
    InspCommService inspCommService;

    @Resource
    DefectMetalLossMapper metalLossMapper;

    // 配置各个表 缺陷类型处显示的名称
    static  Map<String,String> tableShowName=new HashMap<String,String>();
    static
    {
        tableShowName.put("PIC_INSP_TEE","'三通'");
        tableShowName.put("PIC_INSP_VALVE","'阀门'");
        tableShowName.put("PIC_INSP_PIPE_SECTION","'环焊缝'");
        tableShowName.put("PIC_INSP_ELBOW","case WHEN i.ELBOW_TYPE is null THEN '弯头' ELSE  c.short_name END ");
    }

    //配置需要特殊左连接的表
    static  Map<String,String> tableLeft=new HashMap<String,String>();
    static
    {

        tableLeft.put("PIC_INSP_ELBOW".toUpperCase()," left join SYS_BASE_CODE c  on(c.ID_=i.ELBOW_TYPE) ");

    }

    //配置待查询表
    static  Map<String,String> tablePipe=new HashMap<String,String>();
    static {
        tablePipe.put("item1","PIC_INSP_PIPE_SECTION".toUpperCase());
        tablePipe.put("item2","PIC_INSP_ELBOW".toUpperCase());
        tablePipe.put("item3","PIC_INSP_TEE".toUpperCase());
        tablePipe.put("item4","PIC_INSP_VALVE".toUpperCase());
    }

    //配置待查询表
    static  Map<String,String> tableInsp=new HashMap<String,String>();
    static {
        tableInsp.put("item1","PIC_INSP_PIPE_SECTION".toUpperCase());
        tableInsp.put("item2","PIC_INSP_ELBOW".toUpperCase());

    }


    static  Map<String,String> tableFiled=new HashMap<String, String>();
    static {
        String PIC_INSP_DEFECT_META_LOSS="select i.ID_, %s as featureType,i.MILEAGE  as milfage  ,null as length,null as width,   null as maxDepth  ,'' as clock,'' as ps, 1 as type,i.ID_ as idds,'' as REPAIR_SUGGESTION，null AS ERF ";
        String PIC_INSP_DEFECT_CRACK="select i.ID_, %s as featureType,i.MILEAGE  as milfage  ,null as length,null as width,   null as maxDepth  ,'' as clock,'' as ps, 1 as type ,i.ID_ as idds,'' as REPAIR_SUGGESTION,null as CRACK_DEPTH ";
        String PIC_INSP_DEFECT_DEPRESSED="select i.ID_, %s as featureType,i.MILEAGE as milfage ,null as length,null as width, null as maxDepth ,'' as clock,'' as ps, 1 as type ,i.ID_ as idds,'' as REPAIR_SUGGESTION ";
        String PIC_INSP_DEFECT_ELLIPTIC="select i.ID_, %s as  featureType,i.MILEAGE  as milfage  ,null as length,null as width,   '' as noFiled,'' as noclock,'' as ps, 1 as type,i.ID_ as idds,'' as REPAIR_SUGGESTION ";
        String PIC_INSP_DEFECT_GIRTH_WELD="select i.ID_, %s as featureType,i.MILEAGE  as milfage  ,null as length,null as width,   null as noDepth  ,'' as clock,'' as ps, 1 as type,i.ID_ as idds,'' as REPAIR_SUGGESTION ";
        String PIC_INSP_DEFECT_OTHER="select i.ID_, %s as featureType,i.MILEAGE  as milfage  ,null as length,   null as maxDepth  ,'' as clock,'' as ps, 1 as type,i.ID_ as idds,'' as REPAIR_SUGGESTION ,null as width ";
        String PIC_INSP_METAL_EXTERNAL="select i.ID_, %s as featureType,i.MILEAGE  as milfage  ,i.REFERENCE as ref,i.REFERENCE_DISTANCE as refd,   null as clock,null as ps, 1 as type,i.ID_ as idds,'' as DETECTION_DATE ";


        tableFiled.put("PIC_INSP_DEFECT_META_LOSS",PIC_INSP_DEFECT_META_LOSS);
        tableFiled.put("PIC_INSP_DEFECT_CRACK",PIC_INSP_DEFECT_CRACK);
        tableFiled.put("PIC_INSP_DEFECT_DEPRESSED",PIC_INSP_DEFECT_DEPRESSED);
        tableFiled.put("PIC_INSP_DEFECT_ELLIPTIC",PIC_INSP_DEFECT_ELLIPTIC);
        tableFiled.put("PIC_INSP_DEFECT_GIRTH_WELD",PIC_INSP_DEFECT_GIRTH_WELD);
        tableFiled.put("PIC_INSP_DEFECT_OTHER",PIC_INSP_DEFECT_OTHER);
        tableFiled.put("PIC_INSP_METAL_EXTERNAL",PIC_INSP_METAL_EXTERNAL);
    }





    /**
     * 获取表结构
     * @param type
     * @param table
     * @param param
     * @param source
     * @return
     */
    public static String getReferenceTable(String type,String table,Map<String,Object> param,String source)
    {


        StringBuilder sb=new StringBuilder(String.format(tableFiled.get(source),tableShowName.get(table.toUpperCase())));




        sb.append("from ").append(table).append(" i");

        if(tableLeft.get(table.toUpperCase()) != null)
        {
            sb.append(" ").append(tableLeft.get(table.toUpperCase()));
        }
        sb.append(" where i.DELETED=0 ");

        if(!StringUtils.isEmpty((String)param.get("taskId")))
        {
            sb.append(" and i.INSP_TASK_ID = '").append(param.get("taskId")).append("' ");
        }

        if(!StringUtils.isEmpty((String)param.get("taskSegmentId")))
        {
            sb.append(" and i.INSP_SEGMENT_ID = '").append(param.get("taskSegmentId")).append("' ");
        }


        if(!StringUtils.isEmpty((String)param.get("lineId")))
        {
            sb.append(" and i.PIPE_LINE_ID = '").append(param.get("lineId")).append("' ");
        }


        //构建绝对距离查询条件
        if(param.get("beginMileage") != null && ((Double)param.get("beginMileage")) == ((Double)param.get("endMileage")))
        {
            sb.append(" and i.MILEAGE =  ").append(param.get("endMileage")).append(" ");
        }

        if(param.get("beginMileage") != null)
        {
            sb.append(" and i.MILEAGE >= ").append(param.get("beginMileage")).append(" ");
        }

        if(param.get("endMileage") !=null  &&  ((Double)param.get("beginMileage")) != ((Double)param.get("endMileage")))
        {
            sb.append(" and i.MILEAGE < ").append(param.get("endMileage")).append(" ");
        }

        return sb.toString();
    }

    /**
     * 获取依赖
     * @param param
     * @param source
     * @return
     */
    public  String getReference(Map<String,Object> param,String source)
    {
        StringBuilder sql=new StringBuilder("");
        List<String> items= (List<String>) param.get("otherList");


        if (items != null )
        {
            String table=null;
            String type="0";
            for (String item:items)
            {
                if("20".equals(item))
                {
                    continue;
                }
                type="1";
                table=tablePipe.get("item"+item);
                String tables[]=table.split(",");
                for (String t:tables)
                {
                    System.out.println("table:"+table+"\t=\t"+getReferenceTable(type,t,param,source));
                    param.put(table,getReferenceTable(type,t,param,source));
//                    sql.append(" union ").append(getReferenceTable(type,t,param,source));
                }

                table=null;
            }
        }
        return sql.toString();
    }


    /**
     * 参数集中处理
     * @param param
     */

    public  void handlerParam(Map<String,Object> param)
    {

        String beginClock= (String) param.get("beginClock");
        String endClock= (String) param.get("endClock");
        String taskId= (String) param.get("taskId");
        PageHelper.startPage(1, 2);

        Map data=this.inspCommService.queryTaskMileage(taskId);
        BigDecimal beginMileage= (BigDecimal) data.get("BEGINMILEAGE");
        BigDecimal endMileage= (BigDecimal) data.get("ENDMILEAGE");

        //检查绝对距离
        cheackMileage(param,beginMileage,endMileage);

        //获取任务信息
        HashMap task = this.metalLossMapper.findTaskById(taskId);
        param.put("taskDate",task.get("CDATE"));
        param.put("taskType",task.get("DETECTOR_TYPE_NAME"));
        if(param.get("beginName") == null)
        {
            param.put("beginName",task.get("BEGINNAME")==null?"":task.get("BEGINNAME"));
        }
        if(param.get("endName") == null)
        {
            param.put("endName",task.get("ENDNAME")==null?"":task.get("ENDNAME"));
        }
    }


    /**
     * 检查是否需要进行绝对距离计算
     * @param param
     * @param beginMileage
     * @param endMileage
     */
    public static void cheackMileage(Map<String,Object> param,BigDecimal beginMileage,BigDecimal endMileage)
    {

        String c_beginMileage=(String)param.get("beginMileage");
        String c_endMileage=(String)param.get("endMileage");

        Double c_beginMileageDouble = 0d;
        Double c_endMileageDouble = 0d;


        if(!StringUtils.isEmpty((String)param.get("beginMileage")))
        {
            c_beginMileageDouble = Double.parseDouble(c_beginMileage);
            beginMileage = BigDecimal.valueOf(c_beginMileageDouble);
        }
        if(!StringUtils.isEmpty((String)param.get("endMileage")))
        {
            c_endMileageDouble = Double.parseDouble(c_endMileage);
            endMileage = BigDecimal.valueOf(c_endMileageDouble);
        }
        if(Math.abs(c_endMileageDouble) < Math.abs(c_beginMileageDouble))
        {
            Double t = c_beginMileageDouble;
            c_beginMileageDouble = Math.abs(c_endMileageDouble);
            c_endMileageDouble = Math.abs(t);
        }




        if(Math.abs(endMileage.doubleValue()) < Math.abs(beginMileage.doubleValue()))
        {
            BigDecimal t = beginMileage;
            beginMileage = endMileage;
            endMileage = t;
        }
//        if(!StringUtils.isEmpty((String)param.get("beginMileage"))) {
            param.put("beginMileage", beginMileage.doubleValue());//c_beginMileageDouble>0?c_beginMileageDouble-beginMileage.doubleValue():0);
//        }
//        if(!StringUtils.isEmpty((String)param.get("endMileage"))) {
            param.put("endMileage", endMileage.doubleValue());///c_endMileageDouble>0?c_endMileageDouble-beginMileage.doubleValue():endMileage.doubleValue()-beginMileage.doubleValue());
//        }

    }

    public void initPage()
    {
        String currentStr = RequestResponseContext.getRequest().getParameter("current");
        String pageCountStr = RequestResponseContext.getRequest().getParameter("pageCount");
        Integer current =null;
        Integer pageCount= null;
        if(StringUtils.isEmpty(currentStr))
        {
            currentStr = RequestResponseContext.getRequest().getParameter("pageNo");
        }
        if(StringUtils.isEmpty(pageCountStr))
        {
            pageCountStr = RequestResponseContext.getRequest().getParameter("pageSize");
        }

        if(!StringUtils.isEmpty(currentStr))
        {
            current=Integer.parseInt(currentStr);
        }

        if(!StringUtils.isEmpty(pageCountStr))
        {
            pageCount=Integer.parseInt(pageCountStr);
        }
        int pageNo=1;
        int pageSize=10;
        if(null != current)
        {
            pageNo=current;
        }

        if(null != pageCount)
        {
            pageSize=pageCount;
        }
        PageHelper.startPage(pageNo, pageSize);
    }


    /**
     * 设置数据字典表信息
     * @param data
     */
    public void setCodeName(List<HashMap<String,Object>> data)
    {
        for(HashMap map : data)
        {
            if(map.get("DETECTION_TYPE") != null)
            {
                map.put("DETECTION_TYPE", CodeUtil.getName((String)map.get("DETECTION_TYPE")));
            }
            if(map.get("SENSOR_TYPE") != null)
            {
                map.put("SENSOR_TYPE", CodeUtil.getName((String)map.get("SENSOR_TYPE")));
            }
            if(map.get("DETECTOR_TYPE") != null)
            {
                map.put("DETECTOR_TYPE", CodeUtil.getName((String)map.get("DETECTOR_TYPE")));
            }
            if(map.get("ELBOW_TYPE") != null)
            {
                map.put("ELBOW_TYPE", CodeUtil.getName((String)map.get("ELBOW_TYPE")));
            }

        }
    }


    public void handlCeharacteristic(List<HashMap<String,Object>> data,HashMap param)
    {
        setCodeName(data);
        for(HashMap map : data)
        {
            map.put("SEND_DATE",param.get("taskDate"));
        }
    }
}
